import {BrowserWindow, ipcMain} from 'electron'
import Socks5 from "../socks5";
import axios from 'axios'


const createWindow = async () => {

  console.log('-----------createWindow------------')

  const proxy = new Socks5('tunnel-08301515.520300.xyz', 23398, 'guijie', '123456')
  await proxy.start()
  const win = new BrowserWindow({
    width: 1400,
    height: 800,
    webPreferences: {
      // additionalArguments: [],
      // allowRunningInsecureContent: true,
      nodeIntegration: true,
      contextIsolation: false,
      // partition: 'persist:webviewsession',
    },
  });

  win.on('close', (event) => {
    console.log('close')
    // proxy.close()
  });

  // await session.defaultSession.setProxy({
  //   proxyRules: proxy.proxyUrl(),
  // });

  // 拦截和修改请求头
  const filter = {
    urls: ['*://*/*']
  };

  // win.webContents.session.webRequest.onHeadersReceived(filter, (details, callback) => {
  //   const { responseHeaders } = details
  //   if (responseHeaders) {
  //     responseHeaders['Access-Control-Allow-Origin'] = ['*']
  //   }
  //   callback({ responseHeaders })
  // })


  const isXHR = details => {
    const resourceType = details.resourceType
    return resourceType === 'xhr'
  }

  win.webContents.on('did-finish-load', () => {
    console.log('Page has finished loading');
    win.webContents.executeJavaScript(`
      setTimeout(() => {
      const element = document.querySelector('.popper-me');
      if (element) {
        element.style.display = 'none';
      }
      }, 300)
    `);
  });

  win.webContents.on('did-stop-loading', () => {
    console.log('Page has finished loading all resources');
    win.webContents.executeJavaScript(`
      setTimeout(() => {
        const element = document.querySelector('.popper-me');
        if (element) {
          element.style.display = 'none';
        }
      }, 300);
    `);
  });

  const requests = new Map<number, Electron.OnBeforeSendHeadersListenerDetails>();

  win.webContents.session.webRequest.onBeforeRequest(filter, (details, callback) => {
    const headers = {
      'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="126"',
      'Content-Type': 'application/json',
      'X-TOKEN': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyNzY2MDUwLCJuYW1lIjoi5YWs5bCaIiwieHFfaWQiOjM4OTIzOTIsIm51bWJlciI6MTU1ODU3LCJ4cV9nbXRfZXhwaXJlIjoxNzY1Mzc2NzkxLCJ4cV9nbXRfdXBkYXRlIjoxNzM1NDg0MzU3fQ.CDTUYpQYU8JmZFj0rl9iQGw6l-DtJzjfwZtCQWx-zsM',
      'sec-ch-ua-mobile': '?0',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) electron-demo/1.0.0 Chrome/126.0.6478.234 Electron/31.7.6 Safari/537.36',
      'sec-ch-ua-platform': '"Windows"',
      'Accept': '*/*',
      'Origin': 'https://scys.com',
      'Sec-Fetch-Site': 'same-origin',
      'Sec-Fetch-Mode': 'cors',
      'Sec-Fetch-Dest': 'empty',
      'Accept-Encoding': 'gzip, deflate, br, zstd',
      'Accept-Language': 'zh-CN'
    };
    if (isXHR(details)) {
      //先判断本地有没有

      //如果本地有，那么直接使用本地的

      //否则还是远程拉取
      console.log(details.method, details.url, details.uploadData ? details.uploadData.map(d => d.bytes.toString()).join('') : '')
    }

    callback({});
  });

  win.webContents.session.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
    if (isXHR(details)) {
      //需要每个请求的请求头缓存一份，等待后面请求的时候使用

      //将请求参数缓存到map，等待请求完成后再发送，将数据缓存到本地数据库
      const requestId = details.id;
      requests.set(requestId, details);
    }
    callback({cancel: false, requestHeaders: details.requestHeaders});
  })

  win.webContents.session.webRequest.onCompleted(filter, (details) => {
    const args = requests.get(details.id);
    requests.delete(details.id);
    if (details.statusCode === 200 && args) {
      const reqArgs: any = {
        baseURL: args.url,
        method: args.method,
        headers: args.requestHeaders
      }
      if (args.method !== 'GET' && args.uploadData && args.uploadData.length) {
        reqArgs.data = args.uploadData.map(d => d.bytes.toString()).join('')
      }

      axios.request(reqArgs)
        .then(res => {
          // console.log(args.method, args.url, JSON.stringify(res.data))
          //将数据缓存到本地数据库
        })
        .catch(e => {
          console.error(e);
        })
    }
  });

  const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoyNzY2MDUwLCJuYW1lIjoi5YWs5bCaIiwieHFfaWQiOjM4OTIzOTIsIm51bWJlciI6MTU1ODU3LCJ4cV9nbXRfZXhwaXJlIjoxNzY1Mzc2NzkxLCJ4cV9nbXRfdXBkYXRlIjoxNzM1NDg0MzU3fQ.CDTUYpQYU8JmZFj0rl9iQGw6l-DtJzjfwZtCQWx-zsM'
  win.loadURL('https://scys.com').then(() => {
    win.webContents.executeJavaScript(`
      localStorage.setItem('__user_token.v3','${token}');
  `)
  })

}

export const initBrowser = () => {
  ipcMain.handle('openBrowser', async () => {
    await createWindow()
  })
}
